import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { AsyncState } from '..'
import { User, apiGetToken } from '../../api/token'
import { getTokenExpTime, isExp } from '../../util/token'

type UserState = AsyncState & {
    user: User | null;
    token: string | null;
}
const initialState: UserState = {
    status: 'idle',
    error: null,
    user: null,
    token: null
}
export const fetchUser = createAsyncThunk('user/fetchUser', apiGetToken)
export const favoriteSlice = createSlice({
    name: 'user',
    initialState: initialState,
    reducers: {
        loadToken(state) {
            const token = localStorage.getItem('token')
            console.log(token)
            if (token) {
                const expTime = getTokenExpTime(token)
                if (expTime) {
                    if (isExp(expTime)) {
                        state.token = null
                    }else{
                        state.token = token
                    }
                } else {
                    state.token = null
                }
            } else {
                state.token = null
            }
        }
    },
    extraReducers(builder) {
        builder
            .addCase(fetchUser.fulfilled, (state, action) => {
                state.status = 'succeeded'
                state.user = action.payload
            })
            .addCase(fetchUser.pending, (state) => {
                state.status = 'loading'
            })
            .addCase(fetchUser.rejected, (state) => {
                state.status = 'failed'
            })
    }
})

export default favoriteSlice.reducer